﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Web;
using System.Xml;
using System.Web.Caching;
using System.Globalization;
using Gollie.Extensions;
using Gollie.WebCache;

namespace Gollie
{
	public class MySqlErrorCodes : CacheFileDependency
	{
		private static string cacheName = "data_mysqlerrorcodes";
		private Dictionary<int, string> errorCodes = new Dictionary<int,string>();

		public MySqlErrorCodes()
			: base(HttpContext.Current.Server.MapPath("/App_Data/MySqlErrorCode.xml"))
		{
			XmlDocument doc = new XmlDocument();

			doc.Load(this.DependencyPath);

			foreach(XmlNode node in doc.SelectNodes("/gollie/mysqlerrors/mysqlerror"))
			{
				if (node.Name == "mysqlerror")
				{
					XmlAttribute attr = node.Attributes["number"];

					errorCodes[XmlConvert.ToInt32(attr.Value)] = node.InnerXml.Clean();
				}
			}

			doc.RemoveAll();
		}

		public string GetMessage(MySql.Data.MySqlClient.MySqlException exception)
		{
			string exMsg;
			string retVal;
			if (this.errorCodes.TryGetValue(exception.Number, out exMsg))
			{
				string[] args = exception.Message.Split('|');
				object[] convertedArgs = new object[args.Length];
				for (int i = 0; i < args.Length; i++ )
				{
					string arg = args[i];
					if (arg.StartsWith("{d}"))
						convertedArgs[i] = Convert.ToDecimal(arg.Substring(3), CultureInfo.GetCultureInfo("en-US")); //MySQL globalization doesn't seem to work
					else
						convertedArgs[i] = arg;
				}

				retVal = string.Format(exMsg, convertedArgs);
			}
			else
				retVal = "Unhandled SQLException: " + exception.Message;

			return retVal;
		}

		public static MySqlErrorCodes GetInstance()
		{
			return DataCache.GetCacheableObject<MySqlErrorCodes>(cacheName);
		}
	}
}